package com.hmall.trade.listener;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hmall.api.item.ItemClient;
import com.hmall.api.pay.PayClient;
import com.hmall.common.constants.MqConstants;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.domain.po.OrderDetail;
import com.hmall.trade.service.IOrderDetailService;
import com.hmall.trade.service.IOrderService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * TODO
 *
 * @Author mr.wu
 * @Data #{DATE} #{TIME}
 */
@Component
@RequiredArgsConstructor
@GlobalTransactional
@Slf4j
public class OrderDelayMessageListener {

    private final IOrderService orderService;

    private final PayClient payClient;

    private final ItemClient itemClient;

    private final IOrderDetailService orderDetailService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqConstants.DELAY_ORDER_QUEUE_NAME),
            exchange = @Exchange(name = MqConstants.DELAY_EXCHANGE_NAME, delayed = "true"),
            key = MqConstants.DELAY_ORDER_KEY
    ))
    public void createOrderListener(Long orderId){
        if(orderId==null){
            log.error("消息中订单Id为空");
            return;
        }
        //1.查询订单状态
        Order order = orderService.getById(orderId);
        Integer status = order.getStatus();
        //2.未支付，需要查询支付流水状态
        Integer payStatus = null;
        if(status==1){
            payStatus = payClient.selectPay(orderId);
        }
        // 4.判断是否支付
        if(payStatus==3){
            // 4.1.已支付，标记订单状态为已支付
            orderService.markOrderPaySuccess(orderId);
        }else if (payStatus==1){
            //4.2.未支付，取消订单，回滚库存
            payClient.updateStatus(2,orderId);
            //回滚库存
            OrderDetail orderDetail = orderDetailService.getOne(Wrappers.<OrderDetail>lambdaQuery().eq(OrderDetail::getOrderId, orderId));
            itemClient.addStock(orderDetail.getItemId(),orderDetail.getNum());
            orderService.update(Wrappers.<Order>lambdaUpdate().eq(Order::getId, orderId).set(Order::getStatus, 5));
        }

    }
}
